<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from 'vue'
import { useLevelStore } from '@/stores/level'
import { Search, ArrowDown } from '@element-plus/icons-vue'
import { 
    getSubjectList, 
    getQuestionPage,
    questionDelete,
    type Subject,
    type QuestionItem,
    type QuestionPageParams
} from '@/api/juanti'
import { ElMessage, ElMessageBox } from 'element-plus'
import tigan from './tigan.vue'
import { useRouter } from 'vue-router'

const LevelStore = useLevelStore()
const router = useRouter()

// 表单参数
const formInline = reactive({
    id: null as number | null,
    title: '',
    gradeLevel: null as number | null,
    subjectId: null as number | null,
    questionType: null as number | null,
})

// 分页参数
const pageParams = reactive({
    pageIndex: 1,
    pageSize: 10
})

// 表格数据
const tableData = ref<QuestionItem[]>([])
const total = ref(0)
const loading = ref(false)

// 学科列表数据
const subjectList = ref<Subject[]>([])
// 筛选后的学科选项
const subjectOptions = ref<{ value: number; label: string }[]>([])

// 题型选项
const questionTypeOptions = ref([
    { value: 1, label: '单选题' },
    { value: 2, label: '多选题' },
    { value: 3, label: '判断题' },
    { value: 4, label: '填空题' },
    { value: 5, label: '简答题' },
])

// 预览相关状态
const previewVisible = ref(false)
const previewQuestion = ref<QuestionItem | null>(null)

// 添加题目下拉菜单状态
const addDropdownVisible = ref(false)

// 加载学科数据
const loadSubjects = async () => {
    try {
        const response = await getSubjectList()
        
        if (response?.code === 1 && Array.isArray(response?.response)) {
            subjectList.value = response.response
            filterSubjects()
        } else {
            console.error('无效的学科列表响应:', response)
            subjectList.value = []
        }
    } catch (error) {
        console.error('加载学科列表失败:', error)
        subjectList.value = []
    }
}

// 根据年级筛选学科
const filterSubjects = () => {
    if (formInline.gradeLevel) {
        subjectOptions.value = subjectList.value
            .filter(item => item.level === formInline.gradeLevel)
            .map(item => ({
                value: item.id,
                label: item.name
            }))
    } else {
        subjectOptions.value = []
        formInline.subjectId = null
    }
    
    if (formInline.subjectId && 
        !subjectOptions.value.some(opt => opt.value === formInline.subjectId)) {
        formInline.subjectId = null
    }
}

// 获取学科名称
const getSubjectName = (subjectId: number): string => {
    const subject = subjectList.value.find(item => item.id === subjectId)
    return subject ? subject.name : '未知学科'
}

// 获取题型名称
const getQuestionTypeName = (type: number): string => {
    const typeObj = questionTypeOptions.value.find(opt => opt.value === type)
    return typeObj ? typeObj.label : '未知题型'
}

// 加载题目数据
const loadQuestions = async () => {
    try {
        loading.value = true
        
        const params: QuestionPageParams = {
            id: formInline.id || undefined,
            title: formInline.title || undefined,
            level: formInline.gradeLevel || undefined,
            subjectId: formInline.subjectId || undefined,
            questionType: formInline.questionType || undefined,
            pageIndex: pageParams.pageIndex,
            pageSize: pageParams.pageSize
        }
        
        const response = await getQuestionPage(params)
        
        if (response?.code === 1 && response.response) {
            tableData.value = response.response.list || []
            total.value = response.response.total || 0
        } else {
            console.error('题目列表获取失败:', response)
            tableData.value = []
            total.value = 0
        }
    } catch (error) {
        console.error('加载题目列表失败:', error)
        tableData.value = []
        total.value = 0
    } finally {
        loading.value = false
    }
}

// 监听年级变化
watch(() => formInline.gradeLevel, () => {
    filterSubjects()
})

// 初始化加载数据
onMounted(() => {
    loadSubjects()
    loadQuestions()
})

// 查询提交
const onSubmit = () => {
    pageParams.pageIndex = 1
    loadQuestions()
}

// 页码变化处理
const handlePageChange = (currentPage: number) => {
    pageParams.pageIndex = currentPage
    loadQuestions()
}

// 添加题目方法 - 显示下拉菜单
const toggleAddDropdown = () => {
    addDropdownVisible.value = !addDropdownVisible.value
}

// 跳转到对应题型添加页面
const goToAddQuestion = (type: string) => {
    addDropdownVisible.value = false
    router.push(`/${type}`)
}

// 编辑题目方法
const handleEdit = (id: number, type: number) => {
  const typeRoutes: Record<number, string> = {
    1: '/danxuan',
    2: '/duoxuan',
    3: '/panduan',
    4: '/tiankong',
    5: '/jieda'
  }
  
  const route = typeRoutes[type] || '/jieda'
  router.push({
    path: route,
    query: { id }
  })
}

// 预览题目方法
const handlePreview = (id: number) => {
    const question = tableData.value.find(item => item.id === id)
    if (question) {
        previewQuestion.value = question
        previewVisible.value = true
    } else {
        ElMessage.warning('未找到题目信息')
    }
}

// 删除题目方法
const handleDelete = (id: number) => {
  ElMessageBox.confirm('确定要删除这个题目吗？此操作不可撤销。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const response = await questionDelete(id)
      
      if (response?.code === 1) {
        ElMessage.success('题目删除成功')
        // 重新加载数据
        loadQuestions()
      } else {
        ElMessage.error(`删除失败: ${response?.message || '未知错误'}`)
      }
    } catch (error) {
      console.error('删除题目失败:', error)
      ElMessage.error('删除题目失败，请稍后再试')
    }
  }).catch(() => {
    // 用户取消操作
  })
}
</script>

<template>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
            <h3>题目ID:</h3>
            <div style="width: 10px;"></div>
            <el-input 
                v-model="formInline.id" 
                style="width: 180px" 
                placeholder="请输入题目ID"
                type="number"
            />
        </el-form-item>
        <el-form-item>
            <h3>题目内容:</h3>
            <div style="width: 10px;"></div>
            <el-input 
                v-model="formInline.title" 
                style="width: 180px" 
                placeholder="请输入题目内容"
            />
        </el-form-item>
        <el-form-item>
            <h3>年级:</h3>
            <div style="width: 10px;"></div>
            <el-select 
                v-model="formInline.gradeLevel" 
                style="width: 180px" 
                clearable
                placeholder="请选择年级"
            >
                <el-option 
                    v-for="item in LevelStore.list" 
                    :key="item.value" 
                    :label="item.name" 
                    :value="item.value" 
                />
            </el-select>
        </el-form-item>
        
        <el-form-item>
            <h3>学科:</h3>
            <div style="width: 10px;"></div>
            <el-select 
                v-model="formInline.subjectId" 
                style="width: 180px"
                placeholder="请选择学科"
                :disabled="!formInline.gradeLevel"
                clearable
            >
                <el-option 
                    v-for="item in subjectOptions" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value" 
                />
            </el-select>
        </el-form-item>
        
        <el-form-item>
            <h3>题型:</h3>
            <div style="width: 10px;"></div>
            <el-select 
                v-model="formInline.questionType" 
                style="width: 180px"
                placeholder="请选择题型"
                clearable
            >
                <el-option 
                    v-for="item in questionTypeOptions" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value" 
                />
            </el-select>
        </el-form-item>
        
        <el-form-item>
            <el-button type="primary" @click="onSubmit" :icon="Search">查询</el-button>
            
            <!-- 添加题目下拉菜单 - 优化为简洁文字选项 -->
            <div style="position: relative; display: inline-block; margin-left: 10px;">
                <el-button type="primary" @click="toggleAddDropdown">
                    添加<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                
                <div v-if="addDropdownVisible" style="position: absolute; top: 100%; left: 0; z-index: 1000; margin-top: 5px; width: 100%; background: white; border: 1px solid #e4e7ed; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);">
                    <div style="padding: 5px 0;">
                        <div 
                            style="padding: 8px 12px; cursor: pointer; color: #606266;"
                            @click="goToAddQuestion('danxuan')"
                        >
                            单选题
                        </div>
                        <div 
                            style="padding: 8px 12px; cursor: pointer; color: #606266;"
                            @click="goToAddQuestion('duoxuan')"
                        >
                            多选题
                        </div>
                        <div 
                            style="padding: 8px 12px; cursor: pointer; color: #606266;"
                            @click="goToAddQuestion('panduan')"
                        >
                            判断题
                        </div>
                        <div 
                            style="padding: 8px 12px; cursor: pointer; color: #606266;"
                            @click="goToAddQuestion('tiankong')"
                        >
                            填空题
                        </div>
                        <div 
                            style="padding: 8px 12px; cursor: pointer; color: #606266;"
                            @click="goToAddQuestion('jieda')"
                        >
                            简答题
                        </div>
                    </div>
                </div>
            </div>
        </el-form-item>
    </el-form>

    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="70" />
        <el-table-column label="学科" width="100">
            <template #default="{ row }">
                {{ getSubjectName(row.subjectId) }}
            </template>
        </el-table-column>
        <el-table-column label="题型" width="80">
            <template #default="{ row }">
                {{ getQuestionTypeName(row.questionType) }}
            </template>
        </el-table-column>
        <el-table-column label="题干" width="200">
            <template #default="{ row }">
                {{ row.title || row.shortTitle || '无题干信息' }}
            </template>
        </el-table-column>
        <el-table-column prop="score" label="分数" width="70" />
        <el-table-column prop="difficult" label="难度" width="70"/>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column fixed="right" label="操作">
            <template #default="{ row }">
                <el-button @click="handlePreview(row.id)">预览</el-button>
                <el-button @click="handleEdit(row.id, row.questionType)">编辑</el-button>
                <el-button type="danger" @click="handleDelete(row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    
    <div style="margin-top: 20px; display: flex; justify-content: center;">
        <el-pagination 
            background 
            layout="prev, pager, next" 
            :total="total"
            :current-page="pageParams.pageIndex"
            :page-size="pageParams.pageSize"
            @current-change="handlePageChange"
        />
    </div>
    
    <!-- 题目预览弹窗 -->
    <tigan 
        v-model:visible="previewVisible" 
        :question="previewQuestion"
    />
</template>